package com.jian.socks5.udp.handler;

import com.jian.socks5.common.Constants;
import com.jian.socks5.udp.DefaultSocks5UDPPacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.socksx.v5.Socks5AddressType;

import java.net.InetSocketAddress;
import java.util.List;

/***
 *
 * @author Jian
 * @data 2021.06.22
 */
@ChannelHandler.Sharable
public class UDPDatagramHandler extends MessageToMessageDecoder<DatagramPacket> {
    @Override
    protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) {
        InetSocketAddress sender = ctx.channel().attr(Constants.udpClientSenderAddrAttr).get();
        Socks5AddressType socks5AddressType = ctx.channel().attr(Constants.udpClientSenderAddrTypeAttr).get();
        ChannelHandlerContext channelHandlerContext = ctx.channel().attr(Constants.udpClientSenderChannelAttr).get();

        if (channelHandlerContext != null && socks5AddressType!=null && sender != null) {

            InetSocketAddress sender1 = msg.sender();
            String senderIpAndPort = sender1.getHostName() + ":" + sender1.getPort();


            ByteBuf data = msg.content().copy();


            DefaultSocks5UDPPacket defaultSocks5UDPPacket = new DefaultSocks5UDPPacket(sender, Constants.localUdpAddrType, Constants.localUdpAddr, Constants.localUdpPort, data);
            ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(defaultSocks5UDPPacket);
            channelFuture.addListener(future -> {
                if (future.isSuccess()) {
                    System.out.println("转发UDP目标数据到客户端数据成功！");
                }else{
                    System.err.println("转发UDP目标数据到客户端数据失败！");
                }
            });

            /*if(Constants.ipAndPorts.contains(senderIpAndPort)){

            }else {
                System.err.println("收到的服务端UDP包不允许转发至客户端！senderIpAndPort:" + senderIpAndPort);
            }*/
        }
    }
}
